package com.bysc.commentservice.utils;

import com.bysc.commentservice.entity.CommentParent;
import com.bysc.commentservice.entity.CommentPost;
import com.bysc.commentservice.entity.CommentSon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class CommentService {
    /**
     * 赋值发起查询的用户与帖子相关信息
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    public void setUserInfo(Object comment,String commentId,String likeSKey,String collectSKey) {
        boolean isLiked = false;
        boolean isCollected = false;
        // 获取该用户是否点赞过
        if (!StringUtils.isEmpty(likeSKey)) {
            isLiked = redisTemplate.opsForSet().isMember(likeSKey, commentId);
        }
        // 获取该用户是否收藏过
        if (!StringUtils.isEmpty(collectSKey)) {
            redisTemplate.opsForSet().isMember(collectSKey, commentId);
        }
        //判断comment所属类型 可能是CommentPost CommentParent CommentSon
        if (comment instanceof CommentPost) {
            ((CommentPost) comment).setIsLiked(isLiked);
            ((CommentPost) comment).setIsCollected(isCollected);
        } else if(comment instanceof CommentParent) {
            ((CommentParent) comment).setIsLiked(isLiked);
        }else  {
            ((CommentSon) comment).setIsLiked(isLiked);
        }
    }
    public int getCommentCount(String postId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("postId").is(postId));
        query.addCriteria(Criteria.where("isDeleted").is(false));
        Integer count1 = Math.toIntExact(mongoTemplate.count(query, CommentParent.class));
        Integer count2 = Math.toIntExact(mongoTemplate.count(query, CommentSon.class));
        return count1 + count2;
    }
}
